import {
  reqGetCode,
  reqUserRegister,
  reqUserLogin,
  reqUserInfo,
  reqLogout,
} from "@/api";

//user模块的小仓库
const state = {
  userInfo: {},
  //token: getToken(),
};
//mutation是唯一修改state的地方
const mutations = {
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  USERLOGOUT() {
    //state.token = ''
    state.userInfo = {}
    //removeToken()
  }
};
const actions = {
  //获取验证码
  async getCode({commit}, phone) {
    let result = await reqGetCode({phone});
    if (result.code === 0) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //用户注册
  async userRegister({commit}, user) {
    let result = await reqUserRegister(user);
    if (result.code === 0) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //用户登录
  async userLogin({commit}, data) {
    let result = await reqUserLogin(data);
    if (result.code === 0) {
      //持久化存储token
      //setToken(result.data.token);
      //commit("USERLOGIN", result.data.token);
      commit("GETUSERINFO", result.data)
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //获取用户信息
  async getUserInfo({commit}) {
    let result = await reqUserInfo();
    if (result.code === 0) {
      commit("GETUSERINFO", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //退出登录
  async userLogout({commit}) {
    let result = await reqLogout();
    if (result.code === 0) {
      commit("USERLOGOUT");
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  }
};
//计算属性
const getters = {};
export default {
  state,
  mutations,
  actions,
  getters,
};
